package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shop/models"
	"time"
)

type ShopController struct {
	beego.Controller
}
type DataMsg struct {
	Code int         `json:"Code"`
	Msg  string      `json:"Msg"`
	Data interface{} `json:"Data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	Price, _ := c.GetFloat("price", 64)
	Weigth, _ := c.GetInt("Weigth")
	num, _ := c.GetInt("num")
	times := time.Now()
	shop := models.Shop{
		Name:   name,
		Price:  Price,
		Weight: Weigth,
		Num:    num,
		Times:  times,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = DataMsg{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = DataMsg{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	name := c.GetString("name")
	shop, total, err := models.MysqlList(page, pageSize, name)
	if err != nil {
		c.Data["json"] = DataMsg{
			Code: 500,
			Msg:  "分页失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		JsonMSg := make(map[string]interface{})
		JsonMSg["shop"] = shop
		JsonMSg["total"] = total
		c.Data["json"] = DataMsg{
			Code: 200,
			Msg:  "分页成功",
			Data: JsonMSg,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(models.Shop{Id: id}).Error
	if err != nil {
		c.Data["json"] = DataMsg{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = DataMsg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Show() {
	id, _ := c.GetInt("id")
	var shop models.Shop
	err := models.DB.Where("id = ?", id).First(&shop).Error
	if err != nil {
		c.Data["json"] = DataMsg{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = DataMsg{
			Code: 200,
			Msg:  "查询成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Update() {
	name := c.GetString("name")
	Price, _ := c.GetFloat("price", 64)
	Weigth, _ := c.GetInt("Weigth")
	num, _ := c.GetInt("num")
	times := time.Now()
	id, _ := c.GetInt("id")
	shop := models.Shop{
		Name:   name,
		Price:  Price,
		Weight: Weigth,
		Num:    num,
		Times:  times,
	}
	err := models.DB.Where("id = ?", id).Updates(&shop).Error
	if err != nil {
		c.Data["json"] = DataMsg{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = DataMsg{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
